package com.dashboard.reading.service;

import com.User.entity.User;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dashboard.reading.entity.Book;
import com.dashboard.reading.mapper.BookMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.utils.APIRespones;
import com.utils.Utils;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BookService {
    @Autowired
    private BookMapper bookMapper;

    public List<Book> getBookInfo(Integer userId, String keywords, int page, int pageSize, String sortField, String sortOrder) {
        Page<Book> bookPage = new Page<>(page, pageSize);
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("user_id", userId);

        if (keywords != null && !keywords.isEmpty() && !keywords.equals("{}")) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode jsonObject = objectMapper.readTree(keywords);
                String title = jsonObject.get("title") != null ? jsonObject.get("title").asText() : null;
                String type = jsonObject.get("type") != null ? jsonObject.get("type").asText() : null;
                String tags = jsonObject.get("tags") != null ? jsonObject.get("tags").asText() : null;
                String status = jsonObject.get("status") != null ? jsonObject.get("status").asText() : null;
                String author = jsonObject.get("author") != null ? jsonObject.get("author").asText() : null;

                queryWrapper.and(wrapper -> wrapper
                        .like(!StringUtils.isEmpty(title), "title", title)
                        .or()
                        .like(!StringUtils.isEmpty(type), "type", type)
                        .or()
                        .like(!StringUtils.isEmpty(tags), "tags", tags)
                        .or()
                        .like(!StringUtils.isEmpty(status), "status", status)
                        .or()
                        .like(!StringUtils.isEmpty(author), "author", author));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        queryWrapper.orderBy(true, "asc".equalsIgnoreCase(sortOrder), sortField);
        bookMapper.selectPage(bookPage, queryWrapper);
        return bookPage.getRecords();
    }
    @Transactional
    public Book findBookById(Integer bookId) {
        return bookMapper.selectById(bookId);
    }
    @Transactional
    public boolean addBook(Book book) {
        int result = bookMapper.insert(book);
        return result > 0;
    }
    @Transactional
    public boolean updateBook(Book book) {

        int result = bookMapper.updateById(book);
        return result > 0;
    }
    @Transactional
    public boolean deleteBook(Integer bookId) {
        int result = bookMapper.deleteById(bookId);
        return result > 0;
    }
    @Transactional
    public APIRespones uploadBookImage(MultipartFile file,Integer bookId) {
        // 上传头像图片到OSS
        String fileName = null;
        try {
            fileName = Utils.uploadImage(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Book book = bookMapper.selectById(bookId);
        if (book == null) {
            return APIRespones.failure("未找到书籍");
        }

        String bookImageUrl = Utils.generateImageUrl(fileName);
        book.setImage(bookImageUrl);
        int result = bookMapper.updateById(book);
        // 构建成功响应的数据
        Map<String, Object> data = new HashMap<>();
        data.put("message", "头像上传成功");
        data.put("imageUrl",bookImageUrl);
        return APIRespones.success(data);
    }
    public APIRespones updateBookDetails(Book book) {
        UpdateWrapper<Book> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", book.getId())
                .set("reflection", book.getReflection())
                .set("rating", book.getRating());
        System.out.println(book.toString());
        int updatedRows = bookMapper.update(book, updateWrapper);

        if (updatedRows > 0) {
            return APIRespones.success(null);
        } else {
            return APIRespones.failure("Failed to update book details.");
        }
    }

}